package cn.ghx.xboot.douyin;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;


public class SignTool {
    public static String getSignature(String privateKeyStr,
                                      String method, String uri,
                                      long timestamp,
                                      String nonce,
                                      String body) throws Exception {
        //method内容必须大写，如GET、POST，uri不包含域名，必须以'/'开头
        String rawStr = method + "\n" +
                uri + "\n" +
                timestamp + "\n" +
                nonce + "\n" +
                body + "\n";
//        System.out.println("sing raw str : " + rawStr);
        Signature sign = Signature.getInstance("SHA256withRSA");

        if(privateKeyStr.contains("BEGIN PRIVATE KEY")){
            privateKeyStr = privateKeyStr.replace("-----BEGIN PRIVATE KEY-----","");
        }
        if(privateKeyStr.contains("END PRIVATE KEY")){
            privateKeyStr = privateKeyStr.replace("-----END PRIVATE KEY-----","");
        }
        privateKeyStr = privateKeyStr.replaceAll("\r\n","");

        sign.initSign(string2PrivateKey(privateKeyStr));
        sign.update(rawStr.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    public static PrivateKey string2PrivateKey(String privateKeyStr) {
        PrivateKey prvKey = null;
        try {
            byte[] privateBytes = Base64.getDecoder().decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            prvKey = keyFactory.generatePrivate(keySpec);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return prvKey;
    }

}
